import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class 组合总和II解法二 {
    // 直接判断前后是否一样

    public static List<List<Integer>> ans;
    public static List<Integer> path;
    public static int sum,n;
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        // 1 1 2 5 6 7 10
        ans = new ArrayList<>();
        path = new ArrayList<>();
        n = candidates.length;
        Arrays.sort(candidates);
        dfs(candidates,target,0);
        return ans;
    }

    private void dfs(int[] nums, int target, int i) {
        if (target == sum) {
            ans.add(new ArrayList<>(path));
            return;
        }
        for (int j = i; j < n; j++) {
            if (j > i && nums[j] == nums[j - 1]) {
                continue;
            }
            path.add(nums[j]);
            sum += nums[j];
            if (sum > target) {
                path.remove(path.size() - 1);
                sum -= nums[j];
                return;
            }
            dfs(nums,target,j + 1);
            path.remove(path.size() - 1);
            sum -= nums[j];
        }
    }
}
